// import chartColor from '@/styles/chart.scss'
const ColorLevel = 8
/**
 * 合并option配置项
 */
export function mergeOption(param = {}, option, extraOpts) {
  const keys = Object.keys(param)
  keys &&
    keys.forEach((key) => {
      if (key === 'color') {
        option.color = param.color
      } else if (Array.isArray(param[key])) {
        const defaultSetting = option[key]
        if (Array.isArray(defaultSetting)) {
          option[key] = param[key].map((item, i) => {
            return {
              ...option[key][i],
              ...item
            }
          })
        } else {
          option[key] = param[key].map((item) => {
            return {
              ...defaultSetting,
              ...item
            }
          })
        }
      } else {
        option[key] = {
          ...option[key],
          ...param[key]
        }
      }
    })
  return option
}

/**
 * 配置series通用项
 */
export function setSeries({ series = [] }, extraOpts = {}) {
  const data = []
  const stackDataTotal = getStackData(series)
  series.forEach((serie) => {
    let param
    switch (serie.type) {
      case 'bar':
        param = {
          type: 'bar',
          barGap: 0,
          barWidth: 20,
          label: {
            show: extraOpts.hasOwnProperty('barLabelShow') ? extraOpts.barLabelShow : true,
            fontSize: 10,
            formatter({ value, dataIndex }) {
              if (serie.stack) {
                return ((value / stackDataTotal[dataIndex]) * 100).toFixed(1) + '%'
              } else {
                return value
              }
            }
          },
          data: []
        }
        break
      case 'line':
        param = {
          type: 'line',
          label: {
            show: extraOpts.hasOwnProperty('lineLabelShow') ? extraOpts.lineLabelShow : true,
            fontSize: 10
          },
          data: []
        }
        break
      case 'pie':
        param = {
          type: 'pie',
          radius: ['45%', '65%'],
          label: {
            lineHeight: 18,
            formatter({ name, value, percent }) {
              return `${name}(${value}): ${percent}%\n`
            }
          },
          labelLine: {
            length: 10
          },
          labelLayout(params) {
            const isLeft = params.labelRect.x < extraOpts.$getDom().getWidth() / 2
            const points = params.labelLinePoints
            // Update the end point.
            if (!points) {
              return
            }
            points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width
            return {
              labelLinePoints: points
            }
          },
          itemStyle: {
            borderWidth: 1,
            borderColor: '#fff'
          },
          data: []
        }
        break
      case 'scatter':
        param = {
          type: 'scatter',
          symbolSize: 6,
          label: {
            show: true,
            position: [15, -2],
            color: '#999',
            formatter({ data }) {
              return data[2]
            }
          },
          itemStyle: {
            color: '#999'
          },
          emphasis: {
            label: {
              color: '#ff791a'
            },
            itemStyle: {
              color: '#ff791a'
            }
          },
          data: []
        }
        if (extraOpts.yAxis && extraOpts.xAxis) {
          param.markLine = {
            symbol: 'none',
            data: [{ yAxis: extraOpts.yAxis }, { xAxis: extraOpts.xAxis }],
            label: {
              position: 'end',
              color: '#ff791a',
              fontWeight: 'bold'
            },
            lineStyle: {
              type: 'solid',
              color: '#ff791a'
            }
          }
        }
        break
      default:
        break
    }
    data.push(param)
  })
  return data
}

/**
 * 设置基准线
 * @param -> object
 * {
 *    name: String,        基准线名称
 *    labelColor: String,  标签颜色（默认为黑色#666）
 *    dataLabel: String,   标签显示值（默认为当前数据值data）
 *    lineType: String,    基准线类型（默认实线solid）
 *    lineColor: String,   基准线颜色（默认浅黑色#ccc）
 *    data: Number         基准线数值
 * }
 */
export function setMarkLine(param) {
  return {
    name: param.name,
    type: 'line',
    symbol: 'none',
    markLine: {
      silent: true,
      symbol: 'none',
      label: {
        color: param.labelColor || '#666',
        formatter() {
          if (param.dataLabel) return param.dataLabel
        }
      },
      lineStyle: {
        type: param.lineType || 'solid',
        color: param.lineColor || '#ccc'
      },
      data: [{ yAxis: param.data }]
    }
  }
}

/**
 * 设置折线上的散点图
 * @param -> object
 * {
 *    name: String,        散点图名称
 *    yAxisData: Array,    散点对应折线拐点的数据
 *    symbolData: Array,   散点数值大小
 *    linerColor: String,  散点颜色系列从低到高（默认 theme）
 *    zIndex: Number       散点图zIndex层级值（默认99）
 * }
 */
export function setLineScatter(param) {
  const data = param.yAxisData.map((data, i) => {
    return [i, data]
  })
  const symbolMax = Math.max(...param.symbolData)
  const symbolMin = Math.min(...param.symbolData)
  const yAxisMax = Math.max(...param.yAxisData)
  const yAxisMin = Math.min(...param.yAxisData)
  return {
    name: param.name || '',
    type: 'scatter',
    label: {
      show: false
    },
    itemStyle: {
      color({ data }) {
        return getChartColor((param.linerColor = 'theme'), data[1], yAxisMax, yAxisMin)
      },
      opacity: 1
    },
    data,
    symbolSize(data) {
      const index = data[0]
      return getSymbolSize(param.symbolData[index], symbolMax, symbolMin)
    },
    z: param.zIndex || 99
  }
}

/**
 * 获取折线上的散点颜色
 * @linerColor: String
 * @data: Number
 * @yAxisMax: Number
 * @yAxisMin: Number
 */
function getChartColor(linerColor, data, yAxisMax, yAxisMin) {
  let dataLevel = (ColorLevel / (yAxisMax - yAxisMin)) * (data - yAxisMin)
  if (dataLevel === ColorLevel) {
    dataLevel = dataLevel - 1
  }
  // return chartColor[`${linerColor}-light-${Math.floor(dataLevel)}`]
}

/**
 * 获取折线上的散点大小
 * @data: Number
 * @symbolMax: Number
 * @symbolMin: Number
 */
function getSymbolSize(data, symbolMax, symbolMin) {
  const MIN = 20 // 定义最小散点
  const MAX = 50 // 定义最大散点
  const perSymbolSize = (MAX - MIN) / (symbolMax - symbolMin) // 计算每个散点值对应的散点大小
  return (data - MIN) * perSymbolSize + MIN
}

/**
 * 设置legend图例上渐变颜色（前面为transparent，此方法专门为柱图+折线图设置，因为一个legend只能设置所有图例固定宽度和高度）
 * @rate: Number
 * @color: String
 */
export function setBarLineLegendColor(rate, color) {
  return {
    color: {
      type: 'linear',
      x: 0,
      y: 0,
      x2: 1,
      y2: 0,
      colorStops: [
        {
          offset: 0,
          color: 'transparent'
        },
        {
          offset: rate,
          color: 'transparent'
        },
        {
          offset: rate,
          color
        },
        {
          offset: 1,
          color
        }
      ],
      global: false // 缺省为 false
    }
  }
}

export function setSctterLegendColor(name, color) {
  return {
    name,
    icon: 'roundRect',
    itemStyle: {
      borderWidth: 8,
      borderColor: {
        type: 'linear',
        x: 0,
        y: 0,
        x2: 1,
        y2: 0,
        colorStops: [
          {
            offset: 0,
            color: '#fff' // 0% 处的颜色
          },
          {
            offset: 1,
            color: '#fff' // 100% 处的颜色
          }
        ],
        global: false // 缺省为 false
      }
    }
  }
}

function getStackData(series = []) {
  const stackDataTotal = []
  series.forEach((item) => {
    if (item.stack) {
      item.data.forEach((val, i) => {
        if (!stackDataTotal[i]) {
          stackDataTotal[i] = 0
        }
        if (typeof val === 'object') {
          stackDataTotal[i] += val.value
        } else {
          stackDataTotal[i] += val
        }
      })
    }
  })
  return stackDataTotal
}
